package com.gaoch.simweather.ui.weather

import android.graphics.Color
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.observe
import androidx.recyclerview.widget.LinearLayoutManager
import com.gaoch.simweather.R
import com.gaoch.simweather.logic.model.Weather
import com.gaoch.simweather.tools.showToast
import com.gaoch.simweather.ui.place.PlaceAdapter
import kotlinx.android.synthetic.main.fragment_place.*
import kotlinx.android.synthetic.main.hourly.*
import kotlinx.android.synthetic.main.now.*

class WeatherActivity : AppCompatActivity() {

    val viewModel by lazy { ViewModelProvider(this).get(WeatherViewModel::class.java) }
    private lateinit var hourAdapter: HourAdapter
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        /**状态栏沉浸**/
        val decorView=window.decorView
        decorView.systemUiVisibility= View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
        window.statusBarColor= Color.TRANSPARENT

        setContentView(R.layout.activity_weather)

        /**24H天气**/
        val layoutManager= LinearLayoutManager(this,LinearLayoutManager.HORIZONTAL,false)
        hourly_rv.layoutManager=layoutManager
        hourAdapter= HourAdapter(this,viewModel.hourlyWeather)
        hourly_rv.adapter=hourAdapter


        if(viewModel.location.isEmpty()){
            viewModel.location=intent.getStringExtra("location")
        }
        if(viewModel.cityName.isEmpty()){
            viewModel.cityName=intent.getStringExtra("cityName")
        }

        /**当获取到天气信息时，更新UI**/
        viewModel.weatherLiveData.observe(this){
            val weather=it.getOrNull()
            if(weather!=null){
                showWeatherInfo(weather)
                viewModel.hourlyWeather.clear()
                viewModel.hourlyWeather.addAll(weather.hourly)
                hourAdapter.notifyDataSetChanged()
            }else{
                "无法获取天气信息".showToast()
                it.exceptionOrNull()?.printStackTrace()
            }
        }
        viewModel.refreshWeather(viewModel.location)



    }

    private fun showWeatherInfo(weather:Weather) {
        now_cityName.text=viewModel.cityName
        now_temp.text=weather.now.temp
        now_text.text=weather.now.windDir



    }
}